<?php

namespace Beerus\Modules\DesignerAuth\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\cache\EsUpdateCollector;
use Doraemon\cache\Queue;
use Doraemon\cache\User as CacheUser;
use Doraemon\model\AdmOperateLog;
use Doraemon\model\Designer\DesignerOpLog;
use Doraemon\model\DesignerAuth;
use Doraemon\model\DesignerPayService;
use Doraemon\model\DesignerTeam;
use Doraemon\model\Member;
use Doraemon\service\Designer\DesignerDingTalkAlert;
use Doraemon\service\DingTalkAlert;
use Doraemon\service\search\AdmUserSearch;
use Doraemon\service\WechatAlert;
use Doraemon\tools\HhzEnv;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class CancelAuthController extends Controller
{
    // 可操作人员限制
    const OPERATOR_LIST = [
        'yangxuwen',
        'chenanyang',
        'hanlifan',
        'jiaxiaoyu',
        'zhouyinglong',
        'lijiaqi1',
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 取消认证弹框页面
    public function cancelLayer($uid)
    {
        return view('DesignerAuth::audit.cancel_auth', [
            'uid' => $uid
        ]);
    }

    public function submit(Request $request)
    {
        $params = $request->all();
        $uid = $params['uid'];

        if (empty(trim($params['reason']))) {
            return response()->json(['msg' => '操作失败，请填写取消认证的原因', 'code' => 0]);
        }

        $admin_id = Admin::user()->id;
        $admin_name = Admin::user()->username;

        $msg = implode("\n", [
            "操作：取消认证",
            "设计师uid：{$params['uid']}",
            "原因：{$params['reason']}",
            "操作人：{$admin_name}\n",
        ]);
        DesignerDingTalkAlert::sendBeerusDesignerAuthAuditMsg2Operator($uid, $msg);

        $auth_info = DesignerAuth::getByUId($uid);

        // 认证数据
        $update_data = [
            'auth_status' => DesignerAuth::STATUS_AUTH_CANCEL,
            'house_article_audit_status' => DesignerAuth::STATUS_AUDIT_SUPPLEMENT,
            'identity_info_audit_status' => DesignerAuth::STATUS_AUDIT_SUPPLEMENT,
            'is_pay' => DesignerAuth::NOT_PAID,
        ];
        if ($auth_info['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE && !empty($auth_info['expire_time'])) {
            $update_data['expire_time'] = time();
        }
        $res = DesignerAuth::updateInfo($uid, $update_data);

        // 终止会员认证服务记录
        DesignerPayService::update([
            'status' => DesignerPayService::STATUS_END,
            'end_time' => time()
        ], [
            'uid' => $uid,
            'status' => DesignerPayService::STATUS_NORMAL
        ]);

        $auth_info = DesignerAuth::getByUId($uid);
        if ($auth_info['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY) {
            // 如果为机构设计师，处理关联子账号的数据
            $bind_bypass = DesignerTeam::select('*', [
                'org_uid' => $uid,
                'status' => DesignerTeam::STATUS_NORMAL
            ]);

            if (!empty($bind_bypass)) {
                $bypass = array_column($bind_bypass, 'member_uid');

                // 取消子账号认证

                // 开服务记录

                // 用户表身份
            }

            // 处理机构权益
        } elseif ($auth_info['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY_BYPASS) {
            // 如果为子账号，解除和已绑定机构账号的关联关系
            $bind_info = DesignerTeam::get('*', [
                'member_uid' => $uid,
                'status' => DesignerTeam::STATUS_NORMAL
            ]);

            if (!empty($bind_info)) {
                DesignerTeam::update([
                    'status' => DesignerTeam::STATUS_DELETE,
                    'edit_time' => time()
                ], [
                    'id' => $bind_info['id']
                ]);
            }
        }

        // 用户身份变更
        Member::updateUserInfo($uid, [
            'type' => Member::USER_COMMON
        ]);

        // 搜索相关数据同步
        AdmUserSearch::updateAdmUserSearchByUid($uid);
        EsUpdateCollector::insert($uid);
        Queue::insertQueue('User/updateSolr', ['uid' => $uid]);

        // 删除用户缓存信息
        CacheUser::deleteUserInfo($uid);

        AdmOperateLog::addLog($uid, AdmOperateLog::$operate_type['cancel_user_auth'], $admin_id, $admin_name);

        if (empty($res)) {
            return response()->json(['msg' => '取消认证失败，请稍后再试', 'code' => 0]);
        } else {
            return response()->json(['msg' => '取消认证成功', 'code' => 1]);
        }
    }

    public function cancel(Request $request)
    {
        $params = $request->all();

        $admin_id = Admin::user()->id;
        $admin_name = Admin::user()->username;
        $uid = $params['uid'];
        $reason = trim($params['reason']);

        if ((HhzEnv::isProduction() || HhzEnv::isGray()) && !in_array($admin_name, self::OPERATOR_LIST)) {
            return [
                'code' => 0,
                'msg' => '您没有权限操作'
            ];
        }

        if (empty($reason)) {
            return [
                'code' => 0,
                'msg' => '取消认证失败！参数请填写原因'
            ];
        }

        $msg = implode("\n", [
            "操作：取消认证",
            "取消认证原因：{$reason}",
            "设计师uid：{$uid}",
            "操作人：{$admin_name}\n",
        ]);
        DesignerDingTalkAlert::sendBeerusDesignerAuthAuditMsg2Operator($uid, $msg);

        $auth_info = DesignerAuth::getByUId($uid);

        // 认证数据
        $update_data = [
            'auth_status' => DesignerAuth::STATUS_AUTH_CANCEL,
            'house_article_audit_status' => DesignerAuth::STATUS_AUDIT_SUPPLEMENT,
            'identity_info_audit_status' => DesignerAuth::STATUS_AUDIT_SUPPLEMENT,
            'is_pay' => DesignerAuth::NOT_PAID,
        ];
        if ($auth_info['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE && !empty($auth_info['expire_time'])) {
            $update_data['expire_time'] = time();
            $auth_info['expire_time'] = time();
        }
        $res = DesignerAuth::updateInfo($uid, $update_data);

        // 终止会员认证服务记录
        DesignerPayService::update([
            'status' => DesignerPayService::STATUS_END,
            'end_time' => time()
        ], [
            'uid' => $uid,
            'status' => DesignerPayService::STATUS_NORMAL
        ]);

        if ($auth_info['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY) {
            // 如果为机构设计师，处理关联子账号的数据
            $bind_bypass = DesignerTeam::select('*', [
                'org_uid' => $uid,
                'status' => DesignerTeam::STATUS_NORMAL
            ]);

            if (!empty($bind_bypass)) {
                // 处理绑定的子账号
                foreach ($bind_bypass as $bypass) {
                    // 取消子账号的认证 开服务记录 用户表身份
                    $this->cannelAuthChild($bypass['member_uid'], $auth_info, $admin_id, $admin_name);
                    // 解绑子账号
                    DesignerTeam::update([
                        'status' => DesignerTeam::STATUS_DELETE,
                        'edit_time' => time()
                    ], [
                        'id' => $bypass['id']
                    ]);
                }
            }

            // 处理机构权益
        } elseif ($auth_info['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY_BYPASS) {
            // 如果为子账号，解除和已绑定机构账号的关联关系
            $bind_info = DesignerTeam::get('*', [
                'member_uid' => $uid,
                'status' => DesignerTeam::STATUS_NORMAL
            ]);

            if (!empty($bind_info)) {
                DesignerTeam::update([
                    'status' => DesignerTeam::STATUS_DELETE,
                    'edit_time' => time()
                ], [
                    'id' => $bind_info['id']
                ]);
            }
        }

        // 用户身份变更
        Member::updateUserInfo($uid, [
            'type' => Member::AUTH_USER_UNAUTH_DESIGNER
        ]);

        // 搜索相关数据同步
        AdmUserSearch::updateAdmUserSearchByUid($uid);
        EsUpdateCollector::insert($uid);
        Queue::insertQueue('User/updateSolr', ['uid' => $uid]);

        // 删除用户缓存信息
        CacheUser::deleteUserInfo($uid);

        AdmOperateLog::addLog($uid, AdmOperateLog::$operate_type['cancel_user_auth'], $admin_id, $admin_name);

        if (empty($res)) {
            return [
                'code' => 0,
                'msg' => '取消认证失败'
            ];
        } else {
            $id = DesignerOpLog::create([
                'uid' => $uid,
                'op' => DesignerOpLog::AUTH_CANCEL,
                'reason' => $reason,
                'op_time' => date('Y-m-d H:i:s'),
                'admin_id' => $admin_id,
                'admin_name' => $admin_name
            ]);

            if ($id) {
                // 下行消息
                Queue::insertQueue('queue/Sysmsg/Send', [
                    'msgCode' => 712,
                    'to_uid' => $uid,
                ], Queue::QUEUE_DORAEMON);
            }

            return [
                'code' => 1,
                'msg' => '取消认证成功'
            ];
        }
    }

    /**
     * @Notes: 取消子账号的
     * @param $uid
     * @param $auth_info
     * @param $admin_id
     * @param $admin_name
     * @author: weiyizheng
     * @Time: 2022/3/17
     */
    private function cannelAuthChild($uid, $auth_info, $admin_id, $admin_name)
    {
        $reason = "主账号被取消认证";
        // 认证数据
        $update_data = [
            'expire_time' => $auth_info['expire_time'],
            'auth_status' => DesignerAuth::STATUS_AUTH_CANCEL,
            'house_article_audit_status' => DesignerAuth::STATUS_AUDIT_SUPPLEMENT,
            'identity_info_audit_status' => DesignerAuth::STATUS_AUDIT_SUPPLEMENT,
            'is_pay' => DesignerAuth::NOT_PAID,
        ];
        DesignerAuth::updateInfo($uid, $update_data);

        // 终止会员认证服务记录
        DesignerPayService::update([
            'status' => DesignerPayService::STATUS_END,
            'end_time' => time()
        ], [
            'uid' => $uid,
            'status' => DesignerPayService::STATUS_NORMAL
        ]);

        // 用户身份变更
        Member::updateUserInfo($uid, [
            'type' => Member::AUTH_USER_UNAUTH_DESIGNER
        ]);

        // 搜索相关数据同步
        AdmUserSearch::updateAdmUserSearchByUid($uid);
        EsUpdateCollector::insert($uid);
        Queue::insertQueue('User/updateSolr', ['uid' => $uid]);

        // 删除用户缓存信息
        CacheUser::deleteUserInfo($uid);

        $id = DesignerOpLog::create([
            'uid' => $uid,
            'op' => DesignerOpLog::AUTH_CANCEL,
            'reason' => $reason,
            'op_time' => date('Y-m-d H:i:s'),
            'admin_id' => $admin_id,
            'admin_name' => $admin_name
        ]);

        if ($id) {
            // 下行消息
            Queue::insertQueue('queue/Sysmsg/Send', [
                'msgCode' => 712,
                'to_uid' => $uid,
            ], Queue::QUEUE_DORAEMON);
        }
    }
}
